﻿using PermissionManager.Model;
using PermissionsManager.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PermissionManager.BLL
{
    public class MenuAPIService: BaseService<Menu>
    {   /// <summary>
        /// 通过用户Id得到对应的菜单
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<Menu> GetMenusByUserId(int userId)
        {
            List<Menu> menus = new List<Menu>();
            using (var db = new PermissionManagerEntities())
            {
                //二级菜单
                var result = from a in db.AdminUser
                             join b in db.AdminUserRole
                             on a.Id equals b.AdminUserId
                             join c in db.RoleFunctionPermission
                             on b.RoleId equals c.RoleId
                             join e in db.Menu
                             on c.MenuId equals e.Id
                             where a.Id == userId
                             select e;

                var childMenus = result.Distinct().ToList();
                menus.AddRange(childMenus);

                //获取二级菜单对应的父级菜单
                foreach (var item in childMenus)
                {
                    var parent = db.Menu.Where(a => a.Id == item.ParentId).FirstOrDefault();
                    menus.Add(parent);
                }
            }

            return menus;
        }
    }
}
